package com.application.api;

import com.application.module.courseitem.CourseItem;
import com.application.module.study.Study;
import com.jfinal.plugin.activerecord.Record;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;

import java.util.List;

/**
 *
 */
@Controller("/api/study")
public class StudyApiController extends BaseController {

    /*
    观看记录
     */
    public void index() {
        int userid = getCUserId();
        splitPage.getQueryParam().put("userid", userid);
        paging(splitPage, Study.sqlId_apiSelect, Study.sqlId_apiFrom);
        List<Record> list = (List<Record>) splitPage.getList();
        list.forEach(o -> {
            int id = o.getInt("id");
            //int unlocks = CouponUsed.dao.count(id, userid);
            int studyNum = Study.dao.findCount(userid, id);
            int itemNum = CourseItem.dao.findCount(id);
            o.set("studynum", studyNum).set("itemnum", itemNum);
        });
        success(splitPage);
    }


    /**
     * 记录学习时间
     *
     * @param itemId
     * @param duration
     * @param position
     */
    public void save() {
        int userid = getCUserId();
        int itemId = getParaToInt("itemId");
        int duration = getParaToInt("duration");
        Integer length = getParaToInt("length");
        int po = getParaToInt("position");
        Study model = Study.dao.findByCourseItemId(itemId, userid);
        if (model == null) {
            CourseItem item = CourseItem.dao.findById(itemId);
            model = new Study();
            model.setCourse_id(item.getCourse_id());
            model.setCourse_itemid(itemId);
            model.setStudy_time(getDate());
            model.setDuration(duration);
            model.set("position", po).set("length", length)
                    .set("userid", userid).save();
        } else {
            //非首次学习，判断学习时长与总时长
            model.setStudy_time(getDate());
            model.setDuration(duration + model.getDuration());
            model.set("position", po);
            if(model.getDuration() > model.getInt("length")) {
                model.setDuration(model.getInt("length"));
            }
            model.update();
        }

        success(1);
    }
}
